#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/25 09:32:18
'''
import sys
sys.path.append(".")

import re
import os
import datetime
import json
from flask import jsonify, request, g
from flask import Blueprint
from Common.read_excel import ReadExcel

from Common.Utils import Utils, PageParam
from db_logic.client import BllClient
from db_logic.medicament import BllMedicament
from db_logic.user import BllUser
from db_logic.medicament_template import BllMedicamentTemplate
from db_logic.meidcament_variety import BllMedicamentVariety
from models.client_models import EntityClient
from models.medicament_models import EntityMedicament, EntityMedicamentTemplate
from Common.auth import token_auth
from Common.create_barcode import CreateBarcode


tmp_router = Blueprint("drug_tmplate", __name__)



# 试剂入库-模板展示
@tmp_router.route("/show_tmp", methods=["GET", "POST"])
@token_auth.login_required
def show_template():
    client_id = request.values.get("client_id")
    func_type = request.values.get("func_type")
    page = int(request.values.get("page", 1))
    page_size = int(request.values.get("page_size", 10))
    page_param = PageParam(page, page_size)
    data = BllMedicamentTemplate().getAllTemplateList(
        client_id=client_id, 
        func_type=func_type,
        page_param=page_param
        )    
    data = Utils.msyql_table_model(data)
    new_data_list = []
    for i in data:
        all_export_cout=0
        # 添加容错,模板内容为空直接跳过
        if i["template_content"] == 'null' or not i["template_content"]:
            continue
        for a in json.loads(i["template_content"]):
            all_export_cout += int(a.get("export_count", 0))
        new_dic = {
            "all_export_count": all_export_cout,
            **i
        }
        new_data_list.append(new_dic)
    return jsonify(Utils.true_return(data={"total_count":page_param.totalRecords, "data_list":new_data_list}))





# 选择药剂入库
@tmp_router.route("/select_drug", methods=["POST"])
@token_auth.login_required
def select_drug_info():
    seach_word =request.values.get("seach_word")
    func_type = request.values.get("func_type")
    page = int(request.values.get("page", 1))
    page_size = int(request.values.get("page_size", 10))
    page_param = PageParam(page, page_size)
    data_list = BllMedicament().get_drug_info_distinct_list(
        seach_word=seach_word, 
        func_type=func_type,
        page_param=page_param)
    data_list = Utils.msyql_table_model(data_list)
    return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data_list": data_list}))

# 绑定入库
@tmp_router.route("/bind_tmp_enter_warehouse", methods=["GET", "POST"])
@token_auth.login_required
def bind_tmp_input_db():
    tmp_content = request.values.get("tmplate_content")
    customer_id = request.values.get("customer_id", '1002437b-debf-46d6-b186-3e16bcf0cc0f')
    func_type = request.values.get("func_type")
    client_id = request.values.get("client_id")
    # client_id = '1c39cb24-07f8-11ed-abd4-f47b094925e1'
    bar_code = request.values.get("bar_code")
    # user_id = request.values.get("user_id")
    if not bar_code:
        return jsonify(Utils.false_return(msg="条码不能为空"))
    drug_obj = BllMedicament().findEntity(EntityMedicament.bar_code==bar_code)
    if drug_obj:
        return jsonify(Utils.false_return(msg="该药剂已被锁定"))
    else:
        content_tmp = json.loads(tmp_content)
        drug_info = {}
        for k, v in content_tmp.items():
            if v is None or v == "" or v == "null":
                continue
            else:
                drug_info[k] = v
        user_info = g.current_user

        drug_variety = BllMedicamentVariety().createDrugVariety(
            customer_id=customer_id,
            drug_info=drug_info, user_info=user_info
        )

        remain_num = drug_info.get("remain", 0)
        if not remain_num:
            remain_num = drug_info.get("total")
        new_dict = {
            "medicament_id": Utils.UUID(),
            "variety_id": drug_variety.variety_id,
            "bar_code": bar_code,
            "customer_id": customer_id,
            "client_id": client_id,
            "inventory_warning_value":10,
            "shelf_life_warning_value":10,
            "use_days_warning_value":10,
            # "is_supervise":0,
            "put_in_date": Utils.get_str_datetime(),
            "put_in_user_id": user_info.user_id,
            "put_in_user_name": user_info.real_name,
            # "status":1,
            "remain": remain_num,
            "func_type": func_type,
        }
        if len(bar_code) > 10:
            new_dict["status"] = 5
        else:
            new_dict["status"] = 1
        finds_list = dir(EntityMedicament())
        for i in finds_list:
            if i in new_dict.keys():
                continue
            value = drug_info.get(i)
            if value != None:
                new_dict[i] = value
        drug_entity = EntityMedicament(**new_dict)
        try:
            BllMedicament().drugPutIn(
                drug_entity, 
                BllClient().findEntity(EntityClient.client_id==client_id),
                user_info
                )
            return jsonify(Utils.true_return(msg="药剂入库成功"))
        except Exception as error:
            return jsonify(Utils.false_return(msg="数据异常，入库失败: %s" % error))



# 新增试剂模板
@tmp_router.route("/add_tmp", methods=["GET", "POST"])
@token_auth.login_required
def add_tmp_info():
    tmp_name = request.values.get("template_name")
    client_id = request.values.get("client_id")
    func_type = request.values.get("func_type")
    # client_id = '1c39cb24-07f8-11ed-abd4-f47b094925e1'
    tmp_content = request.values.get("template_content")
    # user_id = '4cea74ee-0d8b-11ed-943e-f47b094925e1'
    # user = BllUser().findEntity(user_id)
    user = g.current_user
    client = BllClient().findEntity(client_id)
    sql_all = """
    select bar_code_count, start_bar_code from rms_medicament_template where start_bar_code=(select max(start_bar_code) max_start from rms_medicament_template)
    """
    # 获取最大的条形码和条形码数量
    tmp_obj = BllMedicamentTemplate().execute(sql_all).fetchone()
    if tmp_obj:
        max_barcode = int(tmp_obj.start_bar_code) + int(tmp_obj.bar_code_count)
    else:
        max_barcode = 100001
    start_bar_code = max_barcode

    try:
        if not tmp_content or tmp_content == 'null':
            return jsonify(Utils.false_return(msg="模板内容有误"))
        if not tmp_name:
            tmp_name = f'入库模板_{Utils.getFileName()}'
        if isinstance(tmp_content, str):
            # tmp_content = eval(tmp_content)
            tmp_content = json.loads(tmp_content)
        bar_code_count = 0
        for i in tmp_content:
            bar_code_count += int(i['export_count'])
        
        obj = EntityMedicamentTemplate(
            customer_id=client.customer_id,
            client_id=client.client_id,
            client_name=client.client_name,
            template_name=tmp_name,
            func_type=func_type,
            template_content=json.dumps(tmp_content),
            is_wait_export=1,
            start_bar_code=start_bar_code,
            bar_code_count=bar_code_count,
            create_date=Utils.get_str_datetime(),
            create_user_id=user.user_id,
            create_user_name=user.real_name,

        )
        BllMedicamentTemplate().insert(obj)
        return jsonify(Utils.true_return(msg="添加模板成功"))

    except Exception as error:
        return jsonify(Utils.false_return(msg=f"请求有误:{error}"))




# # 编辑试剂模板
# @tmp_router.route("/update_tmp", methods=["GET", "POST"])
# def modify_tmp():
#     tmp_id = request.values.get("template_id")

# 导入入库模板
@tmp_router.route("/put_in_tmp", methods=["GET", "POST"])
@token_auth.login_required
def import_tmplate():
    try:
        file_path = Utils.getUDiskPath()
        # file_path = request.values.get("file_path")
        if not file_path:
            return jsonify(msg="请插入U盘")
        else:
            client_id = request.values.get("client_id", '')
            template_name = request.values.get("template_name", '')
            func_type = request.values.get("func_type")
            read_excel = ReadExcel(file_path + "/" + template_name)
            sql_all = """
            select bar_code_count, start_bar_code from rms_medicament_template where start_bar_code=(select max(start_bar_code) max_start from rms_medicament_template)
            """
            tmp_obj = BllMedicamentTemplate().execute(sql_all).fetchone()
            if tmp_obj:
                max_barcode = tmp_obj.start_bar_code
                bar_code_count = tmp_obj.bar_code_count
                max_barcode = int(max_barcode) + int(bar_code_count)
            else:
                max_barcode = 100001
            start_bar_code = max_barcode

            result_list = read_excel.read(func_type=str(func_type))
            client_obj = BllClient().findEntity(
                EntityClient.client_id==client_id)
            user_obj = g.current_user
            if result_list:
                inster_obj_list = []
                for value in result_list:
                    total_count = 0
                    template_content_list = eval(value)

                    for template_content in template_content_list:
                        total_count += int(template_content['export_count'])
                    obj = EntityMedicamentTemplate(
                        customer_id=client_obj.customer_id,
                        client_id=client_obj.client_id,
                        client_name=client_obj.client_name,
                        template_name=f'入库模板_{Utils.getFileName()}',
                        template_content=value,
                        is_wait_export = 1,
                        start_bar_code=str(start_bar_code),
                        bar_code_count=total_count,
                        create_date=Utils.get_str_datetime(),
                        create_user_id=user_obj.user_id,
                        create_user_name=user_obj.real_name,
                        func_type=func_type

                    )
                    inster_obj_list.append(obj)
                status = BllMedicamentTemplate().insert_many(inster_obj_list)
                if status:
                    return jsonify(Utils.true_return(msg='导入成功'))
                else:
                    return jsonify(Utils.false_return(msg="入库单异常，导入失败"))
            else:
                return jsonify(Utils.false_return(msg="入库单格式不正确,请检查之后重新导入"))
    except FileNotFoundError as e:
        return jsonify(Utils.false_return(msg='当前U盘下暂无reagentTemplate.xlsx文件'))
    except Exception as error:
        return jsonify(Utils.false_return(msg=f"模板错误：{error}"))




# 删除模板
@tmp_router.route("/del_tmp", methods=["GET", "POST"])
@token_auth.login_required
def remove_tmp():
    tmp_id_list = request.values.get("template_id_list")
    if tmp_id_list:
        BllMedicamentTemplate().del_template_obj(eval(tmp_id_list))
        return Utils.true_return(msg='删除药剂模板成功')
    return Utils.false_return(msg='删除药剂模板失败')


# 读取优盘下的文件列表
@tmp_router.route("/u_file_list", methods=["POST"])
# @token_auth.login_required
def get_file_list():
    # file_path = request.values.get("file_path")
    file_path = Utils.getUDiskPath()
    if not file_path:
        return jsonify(Utils.false_return(msg="请插入U盘"))
    data_file_list = list(filter(lambda x: re.match(
        'tem.*?.xlsx', x), os.listdir(file_path)))
    return jsonify(Utils.true_return(data=data_file_list))
    # return jsonify(Utils.true_return(data=os.listdir(file_path)))


@tmp_router.route("/pring_bar_code", methods=["POST"])
@token_auth.login_required
def print_code_data():
    template_id = request.values.get("template_id")
    # start = request.values.get("start_code")
    # end = request.values.get("end_code")
    # temp_obj_list = BllMedicamentTemplate().findList(EntityMedicamentTemplate.template_id._in(template_id_list)).all()
    obj = CreateBarcode()
    print(template_id)
    temp = BllMedicamentTemplate().findEntity(EntityMedicamentTemplate.template_id == template_id)
    for i in range(int(temp.start_bar_code), int(temp.start_bar_code) + int(temp.bar_code_count)):
        obj.create_Code128_img(str(i))
    return jsonify(Utils.true_return(msg="成功"))
        
# # 获取所有导入模板信息
# @tmp_router.route("/all_tmp", methods=["GET"])
# # @token_auth.login_required
# def get_tmp_all_list():
#     data_list = BllMedicamentTemplate().execute(
#         "select * from rms_medicament_template"
#     )
#     return jsonify(Utils.true_return(data=Utils.msyql_table_model(data_list)))


# @tmp_router.route("/getManufacturerList", methods=["POST"])
# def get_ManufacturerList():
#     data = BllMedicament().execute(
#         "select DISTINCT manufacturer as `value` from rms_medicament where manufacturer is not null and manufacturer != ''"
#     ).fetchall()
#     return jsonify(Utils.true_return(data=Utils.msyql_table_model(data)))


# 获取分组后的试剂列表
@tmp_router.route("/get_drug_group_list", methods=["POST"])
@token_auth.login_required
def drug_group_list():
    data = BllMedicament().drug_group_info_list()
    data_list = Utils.msyql_table_model(data)
    return jsonify(Utils.true_return(data=data_list))
